var items = [];
var windowstyle = GetSystemWindowStyle();
var arrow = GetSystemArrow();
var upArrow = GetSystemUpArrow();
var downArrow = GetSystemDownArrow();
var title = LoadImage("title.png");
var font2 = GetSystemFont();
var bg = LoadImage("bg.png");
var menuname = "none";
var bgsound = LoadSound("cricket.wav");
var map_image = undefined;
function Menu(menunamein,mapimage)
{
	if(menunamein == undefined) menuname = "none";
	else menuname = menunamein;
	if(mapimage != undefined)
		map_image = mapimage;
	if(!this instanceof Menu) return new Menu();
	windowstyle = GetSystemWindowStyle();
	font = GetSystemFont();
	arrow = GetSystemArrow();
	upArrow = GetSystemUpArrow();
	downArrow = GetSystemDownArrow();
	items = [];
}

Menu.prototype.addItem = function(name, desc, callback, color)
{
	if (color == undefined) color = CreateColor(255,255,255);
	var item = {
		name: name,
		desc: desc,
		callback: callback,
		color: color
		};
	
	items.push(item);
}

Menu.prototype.execute  = function(x, y, w, h)
{
	var font = GetSystemFont();
	var font_height = font.getHeight();
	var max_shown = Math.floor(h / font_height);
	var offset = 0;
	var selection = 0;
	if(menuname != "PauseMenu")
		bgsound.play(true);
	
	while(!IsKeyPressed(KEY_ESCAPE))
	{
		if(menuname != "PauseMenu")
			bg.blit(0,0);
		else
		{
			map_image.blit(0,0);
			Rectangle(0, 0, GetScreenWidth(), GetScreenHeight(), CreateColor(0,0,0, 100));
		}
		windowstyle.drawWindow(x, y, w, h)
		for (var i = 0; i < max_shown; i++)
		{
			if(i >= items.length) continue;
			if(selection == i)
			{
			font.setColorMask(CreateColor(255,255,0));
			}
			else
			{
			font.setColorMask(items[i+offset].color);
			}
			font.drawText(x+16, y+i * font_height, items[i+offset].name)
		}
		var gameList = GetGameList();
		if(menuname != "PauseMenu")
			title.blit(0,0);
		if(menuname != "PauseMenu")
			font2.drawText(0, 0, "Sphere "+GetVersionString());
		font2.drawText(x+16, y+160, items[selection].desc);
		//font2.drawText(0,16, "Created by Geek Spot");
		font2.drawText(x-72,y+186, "Up+Down Arrows to move, enter to select");
		arrow.blit(x, y + (selection-offset) * font_height);
		if(offset > 0)
			upArrow.blit(x + w - upArrow.width, y);
		if(offset + max_shown < items.length)
			downArrow.blit(x + w - downArrow.width, y + font_height * max_shown - downArrow.height);
			
		
		FlipScreen();
		
		while(AreKeysLeft())
		{
		switch(GetKey())
		{
			case KEY_UP:
				if(selection > 0)
				{
					selection--;
					if (selection < offset) offset--;
				}
				break;
			case KEY_DOWN:
				if(selection < items.length-1)
				{
					selection++;
					if (selection >= offset + max_shown) offset++;
				}
			break;
			case KEY_ENTER:
				bgsound.stop();
				items[selection].callback();
				return;
			break;
			case KEY_ESCAPE:
				return;
			break;
		}
		}
	}
}